package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

/* 真实的服务 */
func main() {
	rs1 := &Srv{Addr: "127.0.0.1:2003"}
	rs1.Run()
	rs2 := &Srv{Addr: "127.0.0.1:2004"}
	rs2.Run()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	// 主线程结束，协程也就结束了
}

type Srv struct {
	Addr string
}

func (s *Srv) Run() {
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", helloSay)
	server := http.Server{
		Addr:         s.Addr,
		WriteTimeout: 3 * time.Second,
		Handler:      mux,
	}
	fmt.Println("启动成功：", s)
	go func() {
		log.Fatal(server.ListenAndServe())
	}()
}

func helloSay(w http.ResponseWriter, r *http.Request) {
	fmt.Println("[handle a request]: ")
	u := fmt.Sprintln("url path", r.URL.Path)
	f := fmt.Sprintln("the X-Forwarded-For:", r.Header.Get("X-Forwarded-For"))
	xr := fmt.Sprintln("the X-Real-Ip:", r.Header.Get("X-Real-Ip"))
	remoteAddr := fmt.Sprintln("the RemoteAddr:", r.RemoteAddr) // 这个直接从请求中获取的
	io.WriteString(w, u)
	io.WriteString(w, f)
	io.WriteString(w, xr)
	io.WriteString(w, remoteAddr)
}

func simpleHTTP(addr string) {
	http.HandleFunc("/", helloSay)
	err := http.ListenAndServe(":8080", nil)
	if nil != err {
		panic(err)
	}
}
